// 森林经营智能体服务相关的组合式函数
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import * as _ from 'lodash'
import { marked } from 'marked'

// 报表名称映射
const REPORT_NAME_MAP: Record<string, string> = {
  mixed_culture_system: '混交栽培模式',
  high_yield_model: '高产栽培模式',
  forest_intercropping: '林下套种模式',
}

// 报表数据接口
export interface ReportData {
  title: string // 报表标题（中文）
  content: string // 报表内容（Markdown格式原始文本）
  contentHtml: string // 报表内容（编译后的HTML）
  finalContent?: string // 最终结果内容（Markdown格式原始文本）
  finalContentHtml?: string // 最终结果内容（编译后的HTML）
  isComplete: boolean // 是否完成
}

// 图表数据接口
export interface ChartData {
  carbon_data?: Record<string, number[]>
  diameter_data?: Record<string, number[]>
  economic_data?: Record<string, number[]>
  height_data?: Record<string, number[]>
  volume_data?: Record<string, number[]>
  radar_data?: {
    data: Array<{ name: string; value: number[] }>
    indicators: Array<{ max: number; name: string }>
  }
  models?: string[]
  years?: number[]
}

export function useForestService() {
  const loading = ref(false)
  const loadingText = ref('思考中')
  const processing = ref(false)

  const conversationId = ref('')

  let intervalId: number | null = null
  let controller: AbortController | null = null

  // Node ID 到报表标题的映射
  const nodeIdToTitleMap = reactive<Record<string, string>>({})

  // 三种报表的数据
  const reports = reactive<Record<string, ReportData>>({
    mixed_culture_system: {
      title: '混交栽培模式',
      content: '',
      contentHtml: '',
      isComplete: false,
    },
    high_yield_model: {
      title: '高产栽培模式',
      content: '',
      contentHtml: '',
      isComplete: false,
    },
    forest_intercropping: {
      title: '林下套种模式',
      content: '',
      contentHtml: '',
      isComplete: false,
    },
  })

  // 图表数据
  const chartData = ref<ChartData | null>(null)

  // 更新加载文本的方法
  function updateLoadingText() {
    if (!loading.value) return
    const dots = loadingText.value.split('.').length - 1
    loadingText.value = '思考中 ' + '.'.repeat((dots % 3) + 1)
  }

  // 开始加载动画
  function startLoadingAnimation() {
    loading.value = true
    intervalId = window.setInterval(updateLoadingText, 1000)
  }

  // 停止加载动画
  function stopLoadingAnimation() {
    loading.value = false
    if (intervalId) {
      clearInterval(intervalId)
      intervalId = null
    }
  }

  // 停止处理
  const stopProcessing = () => {
    if (controller) {
      controller.abort()
    }
    processing.value = false
    stopLoadingAnimation()
  }

  // 重置报表数据
  const resetReports = () => {
    Object.keys(reports).forEach((key) => {
      reports[key].content = ''
      reports[key].contentHtml = ''
      reports[key].finalContent = undefined
      reports[key].finalContentHtml = undefined
      reports[key].isComplete = false
    })
    Object.keys(nodeIdToTitleMap).forEach((key) => {
      delete nodeIdToTitleMap[key]
    })
    chartData.value = null
  }

  // 处理思考标签并编译 Markdown
  const compileMarkdown = (content: string): string => {
    const parts = content.split(/(<think>|<\/think>)/)
    let processedContent = ''
    let isInThink = false

    for (let i = 0; i < parts.length; i++) {
      if (parts[i] === '<think>') {
        isInThink = true
        continue
      } else if (parts[i] === '</think>') {
        isInThink = false
        continue
      }

      if (parts[i]) {
        const parsed = marked.parse(parts[i])
        if (isInThink) {
          processedContent += `<div style="color:#8b8b8b;">${parsed}</div>`
        } else {
          processedContent += parsed
        }
      }
    }

    return processedContent
  }

  // 发送消息到AI模型
  const sendToAI = async (question: string, currentModel: string, extendData?: any) => {
    startLoadingAnimation()
    processing.value = true
    resetReports()

    try {
      controller = new AbortController()
      const signal = controller.signal

      const url = `${import.meta.env.VITE_API_BASE_URL}/euc/api/chat/message/flux`
      const apiKey = 'app-LL0DDROGsXJn3XCaf1sQgxUM'
      const headers = {
        Authorization: `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
        accept: 'text/event-stream',
      }
      const requestData = {
        inputs: {},
        message: question,
        response_mode: 'streaming',
        conversation_id: '',
        user: 'abc-123',
        files: [],
        model: currentModel,
        ...extendData,
      }

      const response = await fetch(url, {
        signal,
        method: 'POST',
        headers,
        body: JSON.stringify(requestData),
      })

      if (response.ok) {
        await processStreamResponse(response)
      } else {
        throw new Error(`请求失败: ${response.status}`)
      }
    } catch (error) {
      console.error('AI请求失败:', error)
      if (error instanceof Error) {
        ElMessage.error(error.message)
      }
    } finally {
      stopLoadingAnimation()
      processing.value = false
    }
    return reports
  }

  // 处理流式响应
  const processStreamResponse = async (response: Response) => {
    const reader = response.body?.getReader()
    const decoder = new TextDecoder()
    let buffer = ''
    let firstDataReceived = false

    if (reader) {
      let isReading = true
      while (isReading) {
        const { value, done } = await reader.read()
        if (done) {
          isReading = false
          break
        }
        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (line) {
            let json: any = {}

            try {
              // 尝试解析 JSON，支持不同的前缀格式
              if (line.startsWith('data:data:')) {
                json = JSON.parse(line.substring(10))
              } else if (line.startsWith('data: ')) {
                json = JSON.parse(line.substring(6))
              } else if (line.startsWith('data:')) {
                json = JSON.parse(line.substring(5))
              } else {
                json = JSON.parse(line)
              }
            } catch (error) {
              // 解析失败，跳过这一行
              continue
            }

            const eventType = json['event']

            if (eventType === 'workflow_started') {
              conversationId.value = json.conversation_id
            }

            // 处理 node_started 事件，建立 node_id 到 title 的映射
            if (eventType === 'node_started') {
              const nodeData = json.data
              if (nodeData && nodeData.node_type === 'llm' && nodeData.title) {
                const nodeId = nodeData.node_id
                const title = nodeData.title
                // 建立映射关系
                if (REPORT_NAME_MAP[title]) {
                  nodeIdToTitleMap[nodeId] = title
                }
              }
              continue
            }

            // 处理 message 事件，获取报表内容
            if (eventType === 'message') {
              const answer = _.get(json, 'answer')
              const fromVariableSelector = _.get(json, 'from_variable_selector')

              if (answer && fromVariableSelector && Array.isArray(fromVariableSelector)) {
                const nodeId = fromVariableSelector[0]
                const reportKey = nodeIdToTitleMap[nodeId]

                if (reportKey && reports[reportKey]) {
                  // 累积报表内容
                  reports[reportKey].content += answer
                  // 实时编译 Markdown
                  reports[reportKey].contentHtml = compileMarkdown(reports[reportKey].content)

                  if (!firstDataReceived) {
                    stopLoadingAnimation()
                    firstDataReceived = true
                  }
                }
              }
              continue
            }

            // 处理 text_chunk 事件
            if (eventType === 'text_chunk') {
              const text = _.get(json, 'data.text')
              if (text) {
                // text_chunk 可能用于其他内容，这里暂时忽略
                // 如果需要处理，可以根据具体需求添加逻辑
              }
              continue
            }

            // 处理 node_finished 事件，获取最终结果
            if (eventType === 'node_finished') {
              const nodeData = json.data
              if (
                nodeData &&
                nodeData.node_type === 'answer' &&
                nodeData.title &&
                REPORT_NAME_MAP[nodeData.title]
              ) {
                const reportKey = nodeData.title
                const finalAnswer = _.get(nodeData, 'outputs.answer')

                if (finalAnswer && reports[reportKey]) {
                  reports[reportKey].finalContent = finalAnswer
                  // 编译最终结果的 Markdown
                  reports[reportKey].finalContentHtml = compileMarkdown(finalAnswer)
                  reports[reportKey].isComplete = true
                }
              }

              // 图标数据
              if (nodeData && nodeData.node_type === 'code') {
                chartData.value = nodeData.outputs.result
              }
              continue
            }

            // 处理 workflow_finished 事件，可能包含图表数据
            if (eventType === 'workflow_finished') {
              const outputs = _.get(json, 'data.outputs')
              if (outputs && outputs.echart_data) {
                try {
                  // 解析图表数据
                  const echartData =
                    typeof outputs.echart_data === 'string'
                      ? JSON.parse(outputs.echart_data)
                      : outputs.echart_data
                  chartData.value = echartData
                } catch (error) {
                  console.error('解析图表数据失败:', error)
                }
              }
              continue
            }
          }
        }
      }
    }
  }

  return {
    loading,
    loadingText,
    processing,
    sendToAI,
    stopProcessing,
    reports,
    chartData,
    resetReports,
    conversationId,
    processStreamResponse,
  }
}
